package middleware

import (
	"fmt"

	"gitee.com/xinshortlink/internal/dto/resp"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func Recovery(logger *zap.Logger, resp *resp.Util) gin.HandlerFunc {
	return gin.RecoveryWithWriter(&PanicOut{logger: logger}, func(ctx *gin.Context, err any) {
		e := fmt.Errorf("服务器内部错误 err= %v", err)
		resp.Resp(ctx, e, nil)
	})
}

type PanicOut struct {
	logger *zap.Logger
}

func (p *PanicOut) Write(b []byte) (int, error) {
	err := string(b)
	p.logger.Error("服务器内部错误", zap.String("err", err))
	return len(err), nil
}
